{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Help Desk - Easy\n",
    "\n",
    "## Scenario\n",
    "A software company has been successful in selling its products to a number of customer organisations, and there is now a high demand for technical support. There is already a system in place for logging support calls taken over the telephone and assigning them to engineers, but it is based on a series of spreadsheets. With the growing volume of data, using the spreadsheet system is becoming slow, and there is a significant risk that errors will be made.\n",
    "\n",
    "![rel](https://sqlzoo.net/w/images/3/38/Helpdesk.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading spark-stubs, spark-hive\n",
      "Adding Hive conf dir /opt/hive/conf to classpath\n",
      "Creating SparkSession\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "SLF4J: No SLF4J providers were found.\n",
      "SLF4J: Defaulting to no-operation (NOP) logger implementation\n",
      "SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<a target=\"_blank\" href=\"http://jupyter:4040\">Spark UI</a>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36m$ivy.$                                  \n",
       "\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.log4j.{Level, Logger}\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.types._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.functions._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.expressions.Window\n",
       "\n",
       "\u001b[39m\n",
       "\u001b[36mspark\u001b[39m: \u001b[32mSparkSession\u001b[39m = org.apache.spark.sql.SparkSession@695ed324"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import $ivy.`org.apache.spark::spark-sql:3.4.0`\n",
    "\n",
    "import org.apache.log4j.{Level, Logger}\n",
    "Logger.getLogger(\"org\").setLevel(Level.OFF)\n",
    "\n",
    "import org.apache.spark._\n",
    "import org.apache.spark.sql._\n",
    "import org.apache.spark.sql.types._\n",
    "import org.apache.spark.sql.functions._\n",
    "import org.apache.spark.sql.expressions.Window\n",
    "\n",
    "val spark = {\n",
    "    NotebookSparkSession.builder()\n",
    "    .progress(false)\n",
    "    .appName(\"app12-1\")\n",
    "    // .master(\"spark://192.168.31.31:7077\")\n",
    "    .master(\"local[*]\")\n",
    "    .config(\"spark.sql.warehouse.dir\", \n",
    "            \"hdfs://192.168.31.31:9000/user/hive/warehouse\") \n",
    "    .config(\"spark.cores.max\", \"4\") \n",
    "    .config(\"spark.executor.instances\", \"1\") \n",
    "    .config(\"spark.executor.cores\", \"2\") \n",
    "    .config(\"spark.executor.memory\", \"10g\") \n",
    "    .config(\"spark.shuffle.service.enabled\", \"false\") \n",
    "    .config(\"spark.dynamicAllocation.enabled\", \"false\") \n",
    "    .config(\"spark.sql.catalogImplementation\", \"hive\")\n",
    "    .config(\"spark.sql.repl.eagerEval.enabled\", \"true\")\n",
    "    .config(\"spark.driver.allowMultipleContexts\", \"true\")\n",
    "    .getOrCreate()\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36mspark.implicits._\n",
       "\u001b[39m\n",
       "defined \u001b[32mfunction\u001b[39m \u001b[36msc\u001b[39m\n",
       "\u001b[36mhiveCxt\u001b[39m: \u001b[32msql\u001b[39m.\u001b[32mhive\u001b[39m.\u001b[32mHiveContext\u001b[39m = org.apache.spark.sql.hive.HiveContext@7e5d6633"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import spark.implicits._\n",
    "def sc = spark.sparkContext\n",
    "val hiveCxt = new org.apache.spark.sql.hive.HiveContext(sc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "defined \u001b[32mclass\u001b[39m \u001b[36mRichDF\u001b[39m"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "// Credit to Aivean\n",
    "implicit class RichDF(val ds:DataFrame) {\n",
    "    def showHTML(limit: Int = 50, truncate: Int = 100) = {\n",
    "        import xml.Utility.escape\n",
    "        val data = ds.take(limit)\n",
    "        val header = ds.schema.fieldNames.toSeq        \n",
    "        val rows: Seq[Seq[String]] = data.map { row =>\n",
    "          row.toSeq.map {cell =>\n",
    "            val str = cell match {\n",
    "              case null => \"null\"\n",
    "              case binary: Array[Byte] => binary.map(\"%02X\".format(_)).mkString(\"[\", \" \", \"]\")\n",
    "              case array: Array[_] => array.mkString(\"[\", \", \", \"]\")\n",
    "              case seq: Seq[_] => seq.mkString(\"[\", \", \", \"]\")\n",
    "              case _ => cell.toString\n",
    "            }\n",
    "            if (truncate > 0 && str.length > truncate) {\n",
    "              // do not show ellipses for strings shorter than 4 characters.\n",
    "              if (truncate < 4) str.substring(0, truncate)\n",
    "              else str.substring(0, truncate - 3) + \"...\"\n",
    "            } else {\n",
    "              str\n",
    "            }\n",
    "          }: Seq[String]\n",
    "        }\n",
    "    publish.html(s\"\"\" <table>\n",
    "                <tr>\n",
    "                 ${header.map(h => s\"<th>${escape(h)}</th>\").mkString}\n",
    "                </tr>\n",
    "                ${rows.map {row =>\n",
    "                  s\"<tr>${row.map{c => s\"<td>${escape(c)}</td>\" }.mkString}</tr>\"\n",
    "                }.mkString}\n",
    "            </table>\n",
    "        \"\"\")\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[36mshift\u001b[39m: \u001b[32mDataFrame\u001b[39m = [shift_date: string, shift_type: string ... 4 more fields]\n",
       "\u001b[36mstaff\u001b[39m: \u001b[32mDataFrame\u001b[39m = [staff_code: string, first_name: string ... 2 more fields]\n",
       "\u001b[36missue\u001b[39m: \u001b[32mDataFrame\u001b[39m = [call_date: string, call_ref: int ... 5 more fields]\n",
       "\u001b[36mshift_type\u001b[39m: \u001b[32mDataFrame\u001b[39m = [shift_type: string, start_time: string ... 1 more field]\n",
       "\u001b[36mlevel\u001b[39m: \u001b[32mDataFrame\u001b[39m = [level_code: int, manager: string ... 2 more fields]\n",
       "\u001b[36mcustomer\u001b[39m: \u001b[32mDataFrame\u001b[39m = [company_ref: int, company_name: string ... 6 more fields]\n",
       "\u001b[36mcaller\u001b[39m: \u001b[32mDataFrame\u001b[39m = [caller_id: int, company_ref: int ... 2 more fields]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "val shift = hiveCxt.table(\"sqlzoo.Shift\")\n",
    "val staff = hiveCxt.table(\"sqlzoo.Staff\")\n",
    "val issue = hiveCxt.table(\"sqlzoo.Issue\")\n",
    "val shift_type = hiveCxt.table(\"sqlzoo.Shift_type\")\n",
    "val level = hiveCxt.table(\"sqlzoo.Level\")\n",
    "val customer = hiveCxt.table(\"sqlzoo.Customer\")\n",
    "val caller = hiveCxt.table(\"sqlzoo.Caller\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.\n",
    "There are three issues that include the words \"index\" and \"Oracle\". Find the call_date for each of them\n",
    "\n",
    "```\n",
    "+---------------------+----------+\n",
    "| call_date           | call_ref |\n",
    "+---------------------+----------+\n",
    "| 2017-08-12 16:00:00 |     1308 |\n",
    "| 2017-08-16 14:54:00 |     1697 |\n",
    "| 2017-08-16 19:12:00 |     1731 |\n",
    "+---------------------+----------+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>Call_date</th><th>Call_ref</th>\n",
       "                </tr>\n",
       "                <tr><td>2017-08-12 16:00:00.0</td><td>1308</td></tr><tr><td>2017-08-16 14:54:00.0</td><td>1697</td></tr><tr><td>2017-08-16 19:12:00.0</td><td>1731</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(issue.filter((col(\"Detail\").contains(\"index\")) && \n",
    "              (col(\"Detail\").contains(\"Oracle\")))\n",
    " .select(\"Call_date\", \"Call_ref\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.\n",
    "Samantha Hall made three calls on 2017-08-14. Show the date and time for each\n",
    "\n",
    "```\n",
    "+---------------------+------------+-----------+\n",
    "| call_date           | first_name | last_name |\n",
    "+---------------------+------------+-----------+\n",
    "| 2017-08-14 10:10:00 | Samantha   | Hall      |\n",
    "| 2017-08-14 10:49:00 | Samantha   | Hall      |\n",
    "| 2017-08-14 18:18:00 | Samantha   | Hall      |\n",
    "+---------------------+------------+-----------+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>Call_date</th><th>First_name</th><th>Last_name</th>\n",
       "                </tr>\n",
       "                <tr><td>2017-08-14 10:10:00.0</td><td>Samantha</td><td>Hall</td></tr><tr><td>2017-08-14 10:49:00.0</td><td>Samantha</td><td>Hall</td></tr><tr><td>2017-08-14 18:18:00.0</td><td>Samantha</td><td>Hall</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(issue.filter((to_date(col(\"Call_date\"))===\"2017-08-14\"))\n",
    " .join(caller.filter((col(\"First_name\")===\"Samantha\") && \n",
    "                     (col(\"Last_name\")===\"Hall\")), \"Caller_id\")\n",
    " .select(\"Call_date\", \"First_name\", \"Last_name\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.\n",
    "There are 500 calls in the system (roughly). Write a query that shows the number that have each status.\n",
    "\n",
    "```\n",
    "+--------+--------+\n",
    "| status | Volume |\n",
    "+--------+--------+\n",
    "| Closed |    486 |\n",
    "| Open   |     10 |\n",
    "+--------+--------+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>Status</th><th>Volume</th>\n",
       "                </tr>\n",
       "                <tr><td>Open</td><td>10</td></tr><tr><td>Closed</td><td>486</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(issue.groupBy(\"Status\")\n",
    " .agg(count(\"Call_ref\").alias(\"Volume\"))\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.\n",
    "Calls are not normally assigned to a manager but it does happen. How many calls have been assigned to staff who are at Manager Level?\n",
    "\n",
    "```\n",
    "+------+\n",
    "| mlcc |\n",
    "+------+\n",
    "|   51 |\n",
    "+------+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>mlcc</th>\n",
       "                </tr>\n",
       "                <tr><td>51</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(issue.join(staff, (issue(\"Assigned_to\")===staff(\"Staff_code\")))\n",
    " .join(level.filter(col(\"Manager\")===\"Y\"), \"Level_code\")\n",
    " .agg(count(\"Call_ref\").alias(\"mlcc\"))\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.\n",
    "Show the manager for each shift. Your output should include the shift date and type; also the first and last name of the manager.\n",
    "\n",
    "```\n",
    "+------------+------------+------------+-----------+\n",
    "| Shift_date | Shift_type | first_name | last_name |\n",
    "+------------+------------+------------+-----------+\n",
    "| 2017-08-12 | Early      | Logan      | Butler    |\n",
    "| 2017-08-12 | Late       | Ava        | Ellis     |\n",
    "| 2017-08-13 | Early      | Ava        | Ellis     |\n",
    "| 2017-08-13 | Late       | Ava        | Ellis     |\n",
    "| 2017-08-14 | Early      | Logan      | Butler    |\n",
    "| 2017-08-14 | Late       | Logan      | Butler    |\n",
    "| 2017-08-15 | Early      | Logan      | Butler    |\n",
    "| 2017-08-15 | Late       | Logan      | Butler    |\n",
    "| 2017-08-16 | Early      | Logan      | Butler    |\n",
    "| 2017-08-16 | Late       | Logan      | Butler    |\n",
    "+------------+------------+------------+-----------+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>shift_date</th><th>Shift_type</th><th>First_name</th><th>Last_name</th>\n",
       "                </tr>\n",
       "                <tr><td>2017-08-12</td><td>Early</td><td>Logan</td><td>Butler</td></tr><tr><td>2017-08-12</td><td>Late</td><td>Ava</td><td>Ellis</td></tr><tr><td>2017-08-13</td><td>Early</td><td>Ava</td><td>Ellis</td></tr><tr><td>2017-08-13</td><td>Late</td><td>Ava</td><td>Ellis</td></tr><tr><td>2017-08-14</td><td>Early</td><td>Logan</td><td>Butler</td></tr><tr><td>2017-08-14</td><td>Late</td><td>Logan</td><td>Butler</td></tr><tr><td>2017-08-15</td><td>Early</td><td>Logan</td><td>Butler</td></tr><tr><td>2017-08-15</td><td>Late</td><td>Logan</td><td>Butler</td></tr><tr><td>2017-08-16</td><td>Early</td><td>Logan</td><td>Butler</td></tr><tr><td>2017-08-16</td><td>Late</td><td>Logan</td><td>Butler</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(shift.withColumn(\"shift_date\", to_date(col(\"Shift_date\")))\n",
    " .join(staff, (shift(\"Manager\")===staff(\"Staff_code\")))\n",
    " .select(\"shift_date\", \"Shift_type\", \"First_name\", \"Last_name\")\n",
    " .dropDuplicates()\n",
    " .orderBy(\"shift_date\", \"Shift_type\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "spark.stop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Scala",
   "language": "scala",
   "name": "scala"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".sc",
   "mimetype": "text/x-scala",
   "name": "scala",
   "nbconvert_exporter": "script",
   "version": "2.12.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
